f = open("test.txt","r")
f.write("123")
f.close()  # 报错下面代码不会执行，一直占用资源
print(f.closed)

try:
    f = open("test.txt", "r")
    f.write("123")
except Exception as e:
    print(e)
finally:
    f.close()  # 不管有没有写入读取内容都应该关闭文件
    print(f.closed)

try:
    with open("test.txt", "r") as f:  # 自动的帮你调用close()
        f.write("123")
except Exception as e:
    print(e)
finally:
    print(f.closed) # 如果这里是True


# 简洁写法 --当读取中文的时候出现乱码 encoding="utf-8"解决乱码
with open("test.txt", "r",encoding="utf-8") as f:  # 自动的帮你调用close()
    print(f.read())

# errors="ignore"忽视报错
with open("./test.txt", "r",errors="ignore") as f:
    print(f.read())

# 绝对路径
# 第一种方式
with open("D:\\04.project\\2201期8班\\18.文件读写操作\\test2.txt", "r") as f:
    print(f.read())
# 第二种方式
with open(r"D:\04.project\2201期8班\18.文件读写操作\test2.txt", "r") as f:
    print(f.read())
# 第三种方式
with open("D:/04.project/2201期8班/18.文件读写操作/test2.txt", "r") as f:
    print(f.read())

